<template>
    <div class="tag-container">
        <!-- 标签 -->
        <draggable v-if="currentGroup" class="draggable" v-model="currentGroup.tags" item-key="id" handle=".item"
            @end="handleTagDragEnd">
            <template #item="{ element }">
                <div class="text-color item" @contextmenu.prevent="(e) => handleContextMenu(e, element)"
                    @click="handleTagClick(element)">
                    <div class="icon">
                        <el-image :src="getIcon(element.url)"
                            :style="{ width: `${tagIconSize}px`, height: `${tagIconSize}px` }">
                            <template #error>
                                <div class="image-slot">
                                    <el-icon>
                                        <PictureFilled />
                                    </el-icon>
                                </div>
                            </template>
                        </el-image>
                    </div>
                    <div class="name">{{ element.name }}</div>
                </div>
            </template>
        </draggable>
        <div class="text-color item" @click="addTagForm" v-if="currentGroup">
            <div class="icon">
                <el-icon :size="tagIconSize">
                    <Plus />
                </el-icon>
            </div>
            <div class="name">添加</div>
        </div>
        <right-click-menu v-model="currentContextMenu" :data="rightClickMenuList" />
        <!-- 标签新增/修改菜单 -->
        <el-dialog v-model="dialogTagVisible" :title="dialogTagTitle" width="500" draggable overflow
            @close="cancelTagForm" append-to-body>
            <el-form ref="tagFormRef" :model="tagForm" label-width="auto">
                <el-form-item label="标签名称" prop="name">
                    <el-input v-model="tagForm.name" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="网页地址" prop="url">
                    <el-input v-model="tagForm.url" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelTagForm">取消</el-button>
                    <el-button type="primary" @click="submitTagForm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import draggable from 'vuedraggable'
import { v4 as uuidv4 } from 'uuid'

const currentGroup = defineModel({
    type: Object,
    default: null
})
const emit = defineEmits(['update:modelValue', 'change'])

//===============================================================================================================================
// 标签
//===============================================================================================================================
// 标签新增/修改相关状态
const tagIconSize = ref(20)
const tagForm = ref({})
const dialogTagTitle = ref("")
const dialogTagVisible = ref(false)

const addTagForm = () => {
    dialogTagTitle.value = "添加标签"
    dialogTagVisible.value = true
}
const cancelTagForm = () => {
    dialogTagVisible.value = false
    tagForm.value = {}
}
const submitTagForm = () => {
    if (!tagForm.value.id) {
        tagForm.value.id = uuidv4().replaceAll('-', '')
        currentGroup.value.tags.push(tagForm.value)
    }
    sendGroup()
    cancelTagForm()
}
const editTag = (row) => {
    dialogTagTitle.value = "编辑标签"
    dialogTagVisible.value = true
    tagForm.value = row
}
const delTag = (row) => {
    currentGroup.value.tags = currentGroup.value.tags.filter(i => i.id != row.id)
    sendGroup()
}

//===============================================================================================================================
// 标签右键菜单
//===============================================================================================================================
// 拖拽排序处理
const handleTagDragEnd = () => {
    sendGroup()
    ElMessage.success('标签顺序已更新')
}
const sendGroup = () => {
    emit('update:modelValue', currentGroup.value)
    emit('change')
}

//===============================================================================================================================
// 公共方法
//===============================================================================================================================
// 标签点击跳转
const handleTagClick = (tag) => {
    if (tag.url) {
        window.open(tag.url, '_blank')
    } else {
        ElMessage.warning('该标签未配置跳转链接')
    }
}

//获取页面图标
const getIcon = (url) => {
    try {
        const parsedUrl = new URL(url);
        return `${parsedUrl.protocol}//${parsedUrl.host}/favicon.ico`;
    } catch (e) {
        console.error('无效的URL格式');
        return '';
    }
}

//右键菜单状态数据
const rightClickMenuList = ref([
    { action: editTag, actionName: '编辑', icon: 'Edit' },
    { action: delTag, actionName: '删除', icon: 'Delete' },
])
const currentContextMenu = ref({})

// 右键事件处理
const handleContextMenu = (event, obj) => {
    event.preventDefault()
    currentContextMenu.value = {
        data: obj,
        x: event.clientX,
        y: event.clientY,
        show: true
    }
}

</script>

<style scoped lang="scss">

.text-color {
  color: var(--lan-main-font-color);
}

.item {
    text-align: center;
    width: 70px;
    display: inline-block;
    border-radius: 8px;
    padding: 5px;
    height: 50px;
    padding-top: 14px;
    background-color: #f5f7fa99;

    .name {
        font-size: 12px;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        /* 确保文本正常换行 */
        white-space: normal;
    }
}

.item:hover {
    background-color: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
}

.context-menu {
    position: fixed;
    z-index: 3000;
    min-width: 80px;
    background: var(--el-bg-color-overlay);
    border-radius: 6px;
    padding: 6px 0;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin: 0;
    list-style: none;
    font-size: 12px;

    li {
        padding: 8px 16px;
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        transition: all 0.2s;
        color: var(--el-text-color-regular);
    }

    li:hover {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
    }

    .context-menu-enter-active,
    .context-menu-leave-active {
        transition: all 0.15s;
    }

    .context-menu-enter-from,
    .context-menu-leave-to {
        opacity: 0;
        transform: translateY(-10px);
    }
}
</style>